/*
 * @Author: Superficial
 * @Date: 2021-11-05 14:57:20
 * @LastEditTime: 2021-11-05 15:18:38
 * @Description: Category store
 */

import { arrayToTree } from 'performant-array-to-tree'
// import type { TreeProps } from "ant-design-vue";
import http from '@/services/http'
import type { Category } from '@/constants/category'
import type { ResponsePaginationData, GeneralGetPageParams } from '@/constants/request'
import { TreeDataNode } from 'ant-design-vue/lib/vc-tree-select/interface'

export const CATEGORY_API_PATH = '/category'

export interface CategoryTree extends Category {
  children?: Array<CategoryTree>
}
export interface AntdTree {
  children?: Array<CategoryTree>
}

/** 获取分类列表 */
export function getCategories(params: GeneralGetPageParams = {}) {
  return http
    .get<ResponsePaginationData<Category>>(CATEGORY_API_PATH, {
      params,
    })
    .then((response) => {
      const tree = arrayToTree(response.result.data, {
        id: '_id',
        parentId: 'pid',
        childrenField: 'children',
        dataField: null,
      })

      return {
        ...response.result,
        tree: tree as Array<CategoryTree>,
      }
    })
}

/** 获取符合 Antd 的分类树 */
export function getAntdTreeByTree({
  tree,
  valuer,
  disabledWhen,
}: {
  tree: Array<CategoryTree>
  valuer(category: Category): any
  disabledWhen?(category: Category): boolean
}) {
  const toAntdTree = (_tree: Array<CategoryTree>): TreeDataNode[] => {
    return _tree.map((category) => {
      return {
        data: category,
        title: category.name,
        key: valuer(category),
        value: valuer(category),
        disabled: disabledWhen?.(category) ?? false,
        children: toAntdTree(category.children || []),
      }
    })
  }
  return toAntdTree(tree)
}

/** 创建分类 */
export function createCategory(category: Category) {
  return http.post(CATEGORY_API_PATH, category).then((response) => response.result)
}

/** 修改分类 */
export function putCategory(category: Category) {
  return http
    .put<Category>(`${CATEGORY_API_PATH}/${category._id}`, category)
    .then((response) => response.result)
}

/** 删除分类 */
export function deleteCategory(categoryId: string) {
  return http.delete(`${CATEGORY_API_PATH}/${categoryId}`).then((response) => response.result)
}

/** 批量删除分类 */
export function deleteCategories(categoriesIds: string[]) {
  return http
    .delete(CATEGORY_API_PATH, { data: { categorie_ids: categoriesIds } })
    .then((response) => response.result)
}
